/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * ImpuestosFrame.java
 *
 * Created on 01/30/2009, 08:54:18 PM
 */
package org.comercios.reportes;

import org.mybeans.Sesion;
import org.mybeans.RegimenBeans;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.HashMap;
import java.util.Map;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import net.sf.jasperreports.engine.JRException;
import net.sf.jasperreports.engine.JasperCompileManager;
import net.sf.jasperreports.engine.JasperFillManager;
import net.sf.jasperreports.engine.JasperPrint;
import net.sf.jasperreports.engine.JasperReport;
import net.sf.jasperreports.view.JasperViewer;
import org.jdesktop.swingx.autocomplete.AutoCompleteDecorator;

/**
 *
 * @author avbravo
 */
public class ComerciosReportesPorCodigoActividadFrame extends javax.swing.JFrame {

    Sesion sesion;
    RegimenBeans regimenBeans;
    String idRegimenFormulario;
    private String RegimenFormulario = "";
    String Regimen = "";

    /** Creates new form ImpuestosFrame */
    public ComerciosReportesPorCodigoActividadFrame() {
        initComponents();
        sesion = new Sesion();
        sesion.setSeleccionado("no");
        /*
         * Fondo
         */

         
         
         

        jPanelFondo.setOpaque(false);
        setContentPane(jPanelFondo);
        /*
         * fondo
         */

        regimenBeans = new RegimenBeans();
        CargarSubGrupoRegimen();
        AutoCompleteDecorator.decorate(this.jComboBoxSubGrupoRegimen);
        AutoCompleteDecorator.decorate(this.jComboBoxIdRegimen);
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jPanelFondo = new javax.swing.JPanel();
        jLabel3 = new javax.swing.JLabel();
        jComboBoxSubGrupoRegimen = new javax.swing.JComboBox();
        jLabel6 = new javax.swing.JLabel();
        jComboBoxIdRegimen = new javax.swing.JComboBox();
        jButtonCancelar = new javax.swing.JButton();
        jButtonPrevio = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setTitle("COMERCIOS POR ACTIVIDAD");

        jLabel3.setText("Subgrupo");

        jComboBoxSubGrupoRegimen.addItemListener(new java.awt.event.ItemListener() {
            public void itemStateChanged(java.awt.event.ItemEvent evt) {
                jComboBoxSubGrupoRegimenItemStateChanged(evt);
            }
        });
        jComboBoxSubGrupoRegimen.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jComboBoxSubGrupoRegimenActionPerformed(evt);
            }
        });

        jLabel6.setText("Regimen");

        jComboBoxIdRegimen.addItemListener(new java.awt.event.ItemListener() {
            public void itemStateChanged(java.awt.event.ItemEvent evt) {
                jComboBoxIdRegimenItemStateChanged(evt);
            }
        });
        jComboBoxIdRegimen.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jComboBoxIdRegimenActionPerformed(evt);
            }
        });

        jButtonCancelar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/gif/regresar.jpeg"))); // NOI18N
        jButtonCancelar.setToolTipText("Cancelarl");
        jButtonCancelar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButtonCancelarActionPerformed(evt);
            }
        });

        jButtonPrevio.setIcon(new javax.swing.ImageIcon(getClass().getResource("/gif/preview.png"))); // NOI18N
        jButtonPrevio.setToolTipText("Vista Previa");
        jButtonPrevio.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButtonPrevioActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout jPanelFondoLayout = new javax.swing.GroupLayout(jPanelFondo);
        jPanelFondo.setLayout(jPanelFondoLayout);
        jPanelFondoLayout.setHorizontalGroup(
            jPanelFondoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanelFondoLayout.createSequentialGroup()
                .addGroup(jPanelFondoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jPanelFondoLayout.createSequentialGroup()
                        .addGroup(jPanelFondoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jLabel6)
                            .addComponent(jLabel3))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(jPanelFondoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jComboBoxSubGrupoRegimen, javax.swing.GroupLayout.PREFERRED_SIZE, 473, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(jComboBoxIdRegimen, javax.swing.GroupLayout.PREFERRED_SIZE, 389, javax.swing.GroupLayout.PREFERRED_SIZE)))
                    .addGroup(jPanelFondoLayout.createSequentialGroup()
                        .addGap(80, 80, 80)
                        .addComponent(jButtonPrevio, javax.swing.GroupLayout.PREFERRED_SIZE, 95, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jButtonCancelar, javax.swing.GroupLayout.PREFERRED_SIZE, 104, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );
        jPanelFondoLayout.setVerticalGroup(
            jPanelFondoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanelFondoLayout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanelFondoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel3)
                    .addComponent(jComboBoxSubGrupoRegimen, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanelFondoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel6)
                    .addComponent(jComboBoxIdRegimen, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanelFondoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jButtonCancelar, javax.swing.GroupLayout.PREFERRED_SIZE, 50, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jButtonPrevio, javax.swing.GroupLayout.PREFERRED_SIZE, 48, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(37, 37, 37))
        );

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jPanelFondo, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jPanelFondo, javax.swing.GroupLayout.PREFERRED_SIZE, 165, javax.swing.GroupLayout.PREFERRED_SIZE)
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void jComboBoxSubGrupoRegimenItemStateChanged(java.awt.event.ItemEvent evt) {//GEN-FIRST:event_jComboBoxSubGrupoRegimenItemStateChanged
}//GEN-LAST:event_jComboBoxSubGrupoRegimenItemStateChanged

    private void jComboBoxSubGrupoRegimenActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jComboBoxSubGrupoRegimenActionPerformed

        try {
            String temp = (String) jComboBoxSubGrupoRegimen.getSelectedItem();
            int posicion = temp.indexOf("|");

            int posfinal = 0;
            if (posicion <= 0) {
                posfinal = 0;
            } else {
                posfinal = posicion - 1;
            }

            temp = temp.substring(0, posfinal);

            CargarRegimen(temp);


        } catch (Exception ex) {
            JOptionPane.showMessageDialog(this, "Error  " + ex.getMessage(), "ComboBox SubGrupoRegimen ActionPerformed", JOptionPane.ERROR_MESSAGE);
        }
}//GEN-LAST:event_jComboBoxSubGrupoRegimenActionPerformed

    private void jComboBoxIdRegimenItemStateChanged(java.awt.event.ItemEvent evt) {//GEN-FIRST:event_jComboBoxIdRegimenItemStateChanged
        //      }
        //start = false;
}//GEN-LAST:event_jComboBoxIdRegimenItemStateChanged

    private void jComboBoxIdRegimenActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jComboBoxIdRegimenActionPerformed

        try {
            String temp = (String) jComboBoxIdRegimen.getSelectedItem();

            if (temp == null || temp.equals("")) {
                return;
            }
            int posicion = temp.indexOf("|");

            int posfinal = 0;
            if (posicion <= 0) {
                posfinal = 0;
            } else {
                posfinal = posicion - 1;
            }

            temp = temp.substring(0, posfinal);

            this.idRegimenFormulario = temp;
            ConsultarRegimen();


        } catch (Exception ex) {
            JOptionPane.showMessageDialog(this, "Error  " + ex.getMessage(), "ComboBox Regimen ActionPerformed", JOptionPane.ERROR_MESSAGE);
        }
}//GEN-LAST:event_jComboBoxIdRegimenActionPerformed

    private void jButtonCancelarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonCancelarActionPerformed
        // TODO add your handling code here:
        dispose();
    }//GEN-LAST:event_jButtonCancelarActionPerformed

    private void jButtonPrevioActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonPrevioActionPerformed

        String reportSource;
        reportSource = sesion.getRutaReportes() + "ComerciosListadosPorActividad.jrxml";
        String reportDest;
        reportDest = sesion.getRutaDestino() + "ComerciosListadosPorActividad.html";

        Map<String, Object> params = new HashMap<String, Object>();

        try {
            if (sesion.Conectar() == false) {
                JOptionPane.showMessageDialog(this, "No se pudo establecer la conexion", "Mensaje", JOptionPane.INFORMATION_MESSAGE);
                return;
            }
            JasperReport jasperReport =
                    JasperCompileManager.compileReport(reportSource);
            params.put("P_IDMUNICIPIO", sesion.getIdmunicipio());
            params.put("P_MUNICIPIO", sesion.getMunicipio());
            params.put("P_REGIMEN", this.Regimen);
            params.put("P_IDREGIMEN", this.idRegimenFormulario);
            // JasperPrint jasperPrint =
            //JasperFillManager.fillReport(
            //jasperReport, params, new JREmptyDataSource());
            JasperPrint jasperPrint =
                    JasperFillManager.fillReport(
                    jasperReport, params, sesion.con);
            // JasperExportManager.exportReportToHtmlFile(
            //     jasperPrint, reportDest);

            JasperViewer.viewReport(jasperPrint, false);

        } catch (JRException ex) {
            ex.printStackTrace();
            JOptionPane.showMessageDialog(null, "Error " + ex.getMessage(), "Error", JOptionPane.ERROR_MESSAGE);
        }
}//GEN-LAST:event_jButtonPrevioActionPerformed

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {

            public void run() {
                new ComerciosReportesPorCodigoActividadFrame().setVisible(true);
            }
        });
    }

    private void CargarSubGrupoRegimen() {
        try {
            if (sesion.Conectar() == false) {
                JOptionPane.showMessageDialog(this, "No se pudo establecer la conexion", "Mensaje", JOptionPane.INFORMATION_MESSAGE);
                return;
            }
            String sqlquery = "select idsubgruporegimen, subgrupo from subgruporegimen where idmunicipio='" + sesion.getIdmunicipio() + "' and activo='si' order by idsubgruporegimen";
            PreparedStatement psquery = sesion.con.prepareStatement(sqlquery);
            ResultSet rs = psquery.executeQuery();
            jComboBoxSubGrupoRegimen.removeAllItems();
            int count = 0;
            while (rs.next()) {
                String idsubgruporegimen = rs.getString("idsubgruporegimen");
                idsubgruporegimen = idsubgruporegimen + " | " + rs.getString("subgrupo");
                jComboBoxSubGrupoRegimen.insertItemAt(idsubgruporegimen, count);
                count++;
            }
            if (count != 0) {
                jComboBoxSubGrupoRegimen.setSelectedIndex(0);
            }


        } catch (Exception ex) {
            JOptionPane.showMessageDialog(this, "Error " + ex.getMessage(), "Error. CargarSubGrupoRegimen()", JOptionPane.ERROR_MESSAGE);
        }
    }

    /*
     *
     * Cargar el regimen
     */
    private void CargarRegimen(String idsubgruporegimen) {
        try {
            if (sesion.Conectar() == false) {
                JOptionPane.showMessageDialog(this, "No se pudo establecer la conexion", "Mensaje", JOptionPane.INFORMATION_MESSAGE);
                return;
            }
            idsubgruporegimen = idsubgruporegimen.trim();
            String sqlquery = "select idregimen, valor, regimen from regimen where idmunicipio='" + sesion.getIdmunicipio() + "' and activo='si' and idsubgruporegimen='" + idsubgruporegimen + "' order by idregimen";
            PreparedStatement psquery = sesion.con.prepareStatement(sqlquery);
            ResultSet rs = psquery.executeQuery();
            jComboBoxIdRegimen.removeAllItems();
            int count = 0;
            while (rs.next()) {
                String idregimen = rs.getString("idregimen");
                idregimen = idregimen + " | " + String.valueOf(rs.getDouble("valor")) + " | " + rs.getString("regimen");
                jComboBoxIdRegimen.insertItemAt(idregimen, count);
                count++;
            }
            if (count != 0) {
                jComboBoxIdRegimen.setSelectedIndex(0);
            }


        } catch (Exception ex) {
            JOptionPane.showMessageDialog(this, "Error" + ex.getMessage(), "CargarRegimen() ", JOptionPane.ERROR_MESSAGE);
        }
    }

    private void ConsultarRegimen() {
        try {
            String IdRegimen = idRegimenFormulario;
            if (IdRegimen == null || IdRegimen.equals("")) {
                JOptionPane.showMessageDialog(this, "Ingrese el codigo del regimen", "Mensaje", JOptionPane.INFORMATION_MESSAGE);
                return;
            }
            if (sesion.Conectar() == false) {
                JOptionPane.showMessageDialog(this, "No se pudo establecer la conexion", "Mensaje", JOptionPane.INFORMATION_MESSAGE);
                return;
            }

            String sqlquery = "select regimen.* from regimen where regimen.idmunicipio = ? and idregimen = ?";
            PreparedStatement psquery = sesion.con.prepareStatement(sqlquery);
            psquery.setString(1, sesion.getIdmunicipio());
            psquery.setString(2, IdRegimen);
            ResultSet rs = psquery.executeQuery();
            rs.next();
            int x = rs.getRow();
            if (x == 0) {
                JOptionPane.showMessageDialog(this, "No existen registros de regimen con ese codigo", "Mensaje", JOptionPane.INFORMATION_MESSAGE);
                return;
            }
            String activo = rs.getString("activo");
            if (activo.equals("no")) {
                JOptionPane.showMessageDialog(this, "Este regimen esta inactivo", "Mensaje", JOptionPane.INFORMATION_MESSAGE);
                return;
            }
            String IdSubGrupoRegimen = rs.getString("idsubgruporegimen");
            this.Regimen = rs.getString("regimen");
            double Valor = rs.getDouble("valor");
            double LimiteInferior = rs.getDouble("limiteinferior");
            double LimiteSuperior = rs.getDouble("limiteSuperior");

            if (Regimen == null || Regimen.equals("")) {
                JOptionPane.showMessageDialog(this, "El regimen esta en blanco", "Mensaje", JOptionPane.WARNING_MESSAGE);
                return;
            }
            regimenBeans.setIdRegimen(IdRegimen);
            regimenBeans.setIdSubGrupoRegimen(IdSubGrupoRegimen);
            regimenBeans.setRegimen(Regimen);
            regimenBeans.setValor(Valor);
            regimenBeans.setLimiteInferior(LimiteInferior);
            regimenBeans.setLimiteSuperior(LimiteSuperior);
            RegimenFormulario = Regimen;
            repaint();

        } catch (Exception ex) {
            JOptionPane.showMessageDialog(this, "Error " + ex.getMessage(), "ConsultarRegimen() ", JOptionPane.ERROR_MESSAGE);
        }
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton jButtonCancelar;
    private javax.swing.JButton jButtonPrevio;
    private javax.swing.JComboBox jComboBoxIdRegimen;
    private javax.swing.JComboBox jComboBoxSubGrupoRegimen;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel6;
    private javax.swing.JPanel jPanelFondo;
    // End of variables declaration//GEN-END:variables
}
